// 引用未编译的开发环境代码
import { createApp, getDirname, useAddress, readFile, getMIME } from "./src/lib/index.js"
// 引用编译后的生产环境代码
// import { createApp, getDirname, useAddress, readFile, getMIME } from "./package/lib/index.js"
import { join } from "path"

const rootDirname = getDirname(import.meta)

const routes = [
  {
    path: "/",
    handler: ({ readDirname, response }) => {
      const data = readFile(readDirname, "/index.html")
      const type = getMIME("html")
      response.setHeader("Content-Type", `${type};charset=utf-8`)
      return { statusCode: 200, data }
    },
    children: [
      {
        path: "test",
        handler: ({ requestQuery }) => {
          return { statusCode: 200, data: JSON.stringify(requestQuery) }
        }
      }
    ]
  }
]

const app = createApp({
  routes,
  readDirname: join(rootDirname, "/src/public")
})

app
  // 最后执行的回调, 结束请求, 返回数据
  .use(({ response, requestResult }) => {
    const { statusCode = 200, data } = requestResult
    response.statusCode = statusCode
    response.end(data)
  })
  // 开启设置监听
  .listen({ port: 8080 }, server => {
    const { hostname, port } = useAddress(server)
    console.log(`启动成功: http://${hostname}:${port}`)
  })
